<template>
  <view class="exam-audio u-flex" @click="onPlay">
    <view v-show="isTimerPlaying">
      <u-image
        src="@/pageCourse/static/images/audio_play_icon.png"
        width="104"
        height="104"
      ></u-image>
    </view>
    <view v-show="!isTimerPlaying">
      <u-image
        src="@/pageCourse/static/images/audio_pause_icon.png"
        width="104"
        height="104"
      ></u-image>
    </view>
    <view class="title">听力文件</view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'BaseAudio',
  props: {
    fileurl: {
      type: String,
      default: '',
    },
    index: {
      type: Number,
      default: 0,
    },
    palyIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      audioContext: null,
      isTimerPlaying: true, // 是否处于暂停状态
    }
  },
  watch: {
    palyIndex() {
      if (this.audioContext && this.palyIndex != this.index) {
        this.audioContext.pause()
        this.isTimerPlaying = true
      }
    },
  },
  mounted() {
    this.audioContext = uni.createInnerAudioContext()
    this.audioContext.src = this.fileurl
  },
  methods: {
    // 开始/继续播放时
    onPlay() {
      if (this.isTimerPlaying) {
        this.isTimerPlaying = false
        this.audioContext.play()
        this.$emit('play', this.index)
      } else {
        this.isTimerPlaying = true
        this.audioContext.pause()
      }
    },
  },
  destroyed() {
    this.audioContext = null
  },
}
</script>

<style lang="scss" scoped>
.exam-audio {
  .title {
    font-size: 28rpx;
    color: #303133;
    margin-left: 24rpx;
  }
}
</style>
